package com.iqoo.store.servlet;

import com.iqoo.store.model.User;
import com.iqoo.store.dao.UserDao;
import com.iqoo.store.dao.ProductDao;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserDao userDao = new UserDao();
    private ProductDao productDao = new ProductDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirm_password");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");

        // 验证输入信息
        if(!password.equals(confirmPassword)) {
            request.setAttribute("error", "密码不一致");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        // 检查用户名是否存在
        User user = userDao.login(username);
        if(user != null) {
            request.setAttribute("error", "用户名已存在");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        // 创建用户对象
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password); // 建议加密存储密码
        newUser.setEmail(email);
        newUser.setPhone(phone);
        newUser.setRole(0);

        // 保存用户信息
        userDao.register(newUser);

        // 重定向到登录页面
        response.sendRedirect("login.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理 GET 请求（如果需要）
    }
}